package sn_log;

import java.io.File;
import java.net.DatagramSocket;
import java.net.ServerSocket;

import soar.basic.*;

import sn_log.share.*;
import sn_log.worker.Worker;
import sn_log.monitor.Monitor;

public class Server
{
    private String __CLASS__=Server.class.getName();

    public boolean start(boolean debug)
    {//{{{
        Cnfg cnfg=Cnfg.getInstance();

        if(!debug)
        {
            int res=Errlog.init("sn_log", cnfg.log.location);
            if(res != 0)
            {
                System.out.println(__CLASS__+": Errlog.init("+
                        cnfg.log.location+") fail, res:"+res);
                return false;
            }
        }

        String dir=cnfg.customlog.location;
        if(!cnfg.customlog.location.substring(0, 1).equals("/"))
            dir=(new File(".").getAbsolutePath())+"/"+dir;
        File d=new File(dir);
        if(d.exists())
        {
            if(!d.isDirectory() ||
                    !d.canRead() || !d.canWrite() || !d.canExecute())
            {
                System.out.println(__CLASS__+
                        ": customlog.location mode invalid");
                return false;
            }
        }
        else
        {
            if(!d.mkdir())
            {
                System.out.println(__CLASS__+
                        ": customlog.location mode invalid");
                return false;
            }
        }

        try
        {
            DatagramSocket server_sock=
                new DatagramSocket(cnfg.access.server_port);
            new Worker(server_sock).start();

            ServerSocket monitor_sock=
                new ServerSocket(cnfg.access.monitor_port);
            new Monitor(monitor_sock).start();

            server_sock.close();
            monitor_sock.close();
        }
        catch(Exception e)
        {
            System.out.println(__CLASS__+": init access ports fail: "+
                    e.toString());
            return false;
        }

        return true;
    }//}}}

    public static void main(String[] args)
    {//{{{
        if(!Cnfg.getInstance().load())
            return;

        boolean debug=false;
        if(args.length > 0)
        {
            String opt=args[0].toUpperCase();
            if(opt.equals("DEBUG"))
                debug=true;
        }
        new Server().start(debug);
    }//}}}
}
